package com.judian.smart.util;

import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.judian.smart.R;
import com.judian.smart.base.MyApplication;
import com.judian.smart.constant.Constants;
import com.judian.smart.model.Device;
import com.judian.smart.model.Floor;
import com.judian.smart.model.GateWay;
import com.judian.smart.model.Mode;
import com.judian.smart.model.ModeList;
import com.judian.smart.model.ProCase;
import com.judian.smart.model.RedInfra;
import com.judian.smart.model.Room;
import com.judian.smart.model.User;
import com.judian.smart.proxy.WidgetDAOProxy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;

public class CaseFileUtil {
    /**
     * 对下载的专案创建一个新的db文件
     * create a new db file for downloaded project
     *
     * @param response    下载回来的数据库信息
     * @param projectName 创建对应的文件夹名称
     * @param isCover     是否为覆盖 true -> 覆盖  false -> 不覆盖
     * @param rootVersion 下载的专案指定的版本 我的云家庭 1  指定云家庭 2
     * @throws IOException 可能会抛出FileNotFoundException,IOException 交由调用者处理
     */
    public static void newCaseFile(Response<ResponseBody> response, String projectName, boolean isCover, int rootVersion) throws IOException {
        ProCase proCase;
        //创建数据库文件
        String path = MyApplication.getInstance().getRootPath();
        File f = new File(path);
        if (!f.exists())
            f.mkdir();
        File sd = new File(path, projectName);
        if (!sd.exists())
            sd.mkdir();
        final String fileName = path
                + File.separator + projectName + File.separator
                + "homedatabases.db";

        long currentLength = 0;
        OutputStream os = new FileOutputStream(fileName);
        InputStream is = response.body().byteStream();
        long totalLength = response.body().contentLength();

        int len;
        byte[] buff = new byte[8192];

        while ((len = is.read(buff)) != -1) {
            os.write(buff, 0, len);
            os.flush();
            currentLength += len;
        }
        if (currentLength >= totalLength) {

            String proCaseKey = AppTools.getSystemTime();
            if (!isCover) {
                ///不覆盖则创建新专案
                proCase = new ProCase();
                proCase.setProCaseName(projectName);
                proCase.setProCaseAlia(projectName);
                proCase.setProCaseKey(proCaseKey);
                proCase.setProCaseImage(Constants.PROCASEIMAGEPATH);
                ProCaseUtils.getInstance().addProCase(proCase);
            } else {
                //如果覆盖则取出对应的专案
                proCase = ProCaseUtils.getInstance().judgeName(projectName);
            }

            updata(fileName);

            ProCaseUtils.getInstance().updateProCaseIndex(1, proCase.getProCaseKey());
            WidgetDAOProxy.instance = null;
            String rootPath = MyApplication.getInstance()
                    .getRootPath()
                    + File.separator
                    + proCase.getProCaseAlia()
                    + File.separator + "homedatabases.db";
            ProjectUtils.getRootPath().setRootPath(rootPath);
            ProjectUtils.getRootPath().setRootName(proCase.getProCaseName());
            ProjectUtils.getRootPath().setRootImage(proCase.getProCaseImage());
            //从服务器上下载的专案统一设置
            ProjectUtils.getRootPath().setRootVersion(rootVersion);
            ProjectUtils.saveRootPath();
//                this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        MainActivity.getMInstance().updateFresh();
//                    }
//                });
//                break;
        }
        is.close();
        os.close();

    }

    public static void updata(String fileName) {
        //d打开数据库
        SQLiteDatabase database =
                SQLiteDatabase.openOrCreateDatabase(new File(fileName), null);

        //复制数据库数据
        List<Room> listRoom = UpdataAndDownload.getRoom(database);
        List<Device> listDevice = UpdataAndDownload.getDevices(database);
        List<RedInfra> listRedFra = UpdataAndDownload.getInfrareds(database);
        List<Mode> listMode = UpdataAndDownload.getMode(database);
        List<ModeList> listModeList = UpdataAndDownload.getModeList(database);
        List<GateWay> listGateWay = UpdataAndDownload.getGateWay(database);
        List<User> listUser = new ArrayList<>();
        //Ling 2019.8.27 下载的专案不需要复制权限,只需要加入自己的权限

        List<Floor> listFloor = UpdataAndDownload.getFloor(database);
        database.close();
        //删除数据库
        File file = new File(fileName);
        file.delete();

        //将新的数据库加入原方案文件
        FileOutputStream fos;
        InputStream is;
        try {
            is = MyApplication.getInstance().getResources()
                    .openRawResource(R.raw.homedatabases);
            fos = new FileOutputStream(fileName);
            byte[] buffer = new byte[8192];
            int count;
            while ((count = is.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
                fos.flush();
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        //打开新的数据库并把原数据库数据复制到新数据库
        SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(new File(fileName), null);
        if (listRoom.size() > 0) {
            UpdataAndDownload.deleteAllRoom(db1);
        }

        for (Room room : listRoom) {
            UpdataAndDownload.insertRoom(db1, room);
        }

        for (int j = 0; j < listDevice.size(); j++) {
            UpdataAndDownload.insertDevice(db1, listDevice.get(j));
        }
        for (int j = 0; j < listRedFra.size(); j++) {
            UpdataAndDownload.insertInfrad(db1, listRedFra.get(j));
        }
        for (int j = 0; j < listMode.size(); j++) {
            UpdataAndDownload.insertMode(db1, listMode.get(j));
        }
        for (int j = 0; j < listModeList.size(); j++) {
            UpdataAndDownload.insertModeList(db1, listModeList.get(j));
        }
        for (int j = 0; j < listGateWay.size(); j++) {
            UpdataAndDownload.insertGateWay(db1, listGateWay.get(j));
        }
        for (int j = 0; j < listUser.size(); j++) {
            UpdataAndDownload.insertUser(db1, listUser.get(j));
        }
        for (int j = 0; j < listFloor.size(); j++) {
            UpdataAndDownload.insertFloor(db1, listFloor.get(j));
        }
    }

    public static void saveVersionFile(Response<ResponseBody> response, String SavePath) {
        try {
            File f = new File(SavePath);
            if (!f.exists())
                f.mkdir();

            final String fileName = SavePath + File.separator + "music.apk";

            long currentLength = 0;
            OutputStream os = new FileOutputStream(fileName);
            InputStream is = response.body().byteStream();
            long totalLength = response.body().contentLength();

            int len;
            byte[] buff = new byte[8192];
            while ((len = is.read(buff)) != -1) {
                os.write(buff, 0, len);
                os.flush();
                currentLength += len;
                if (currentLength >= totalLength) {

                }
            }
            is.close();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
